package com.jerehedu.myapplication34.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.jerehedu.myapplication34.R;
import com.jerehedu.myapplication34.adapter.MyGridAdapter;
import com.jerehedu.myapplication34.dao.BookDao;
import com.jerehedu.myapplication34.entrty.Book;
import com.jerehedu.myapplication34.view.MyGridView;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

public class MainActivity extends AppCompatActivity {
    private MyGridView gridView;
    private MyGridAdapter adapter;
    private List<Book> mData;
    private BookDao dao;
    private ImageView img1;
    private PopupWindow addBook,delBook,login;
    private boolean isLongClickState=false;
    private Button chooseAll;
    private TextView bookShop;
    private ImageView search;
    private ImageView drawerImg;
    private RelativeLayout setting,about,sign;
    private CircleImageView centerHead,civ_login_qq;

    private Tencent mTencent;
    private String APP_ID = "222222";
    private IUiListener loginListener;
    private String SCOPE = "all";
    private IUiListener userInfoListener;
    private String figureurl_qq_1;
    private TextView denglv;
    private static boolean isExit=false;
    private String QQId;
    //按两次退出
    Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit=false;
        }
    };



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit(){
        if(isLongClickState){
            for (Book book : mData) {
                book.setIsCheck(0);
                book.setIsShow(0);
            }
            chooseAll.setText("全选");
            delBook.dismiss();
            isLongClickState=false;
            adapter.notifyDataSetChanged();
        }else {
            if(!isExit){
                isExit=true;
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                //利用handler延迟发送更改状态信息
                mHandler.sendEmptyMessageDelayed(0,2000);
            }else {
                finish();
                System.exit(0);
            }
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dao=new BookDao(MainActivity.this);
        img1=(ImageView)findViewById(R.id.imageView1);
        bookShop=(TextView)findViewById(R.id.bookShop);
        denglv=(TextView)findViewById(R.id.denglv);
        search=(ImageView)findViewById(R.id.search);
        drawerImg=(ImageView)findViewById(R.id.drawerImg);
        setting=(RelativeLayout)findViewById(R.id.setting);
        centerHead=(CircleImageView)findViewById(R.id.centerHead);
        about=(RelativeLayout)findViewById(R.id.about);
        sign=(RelativeLayout)findViewById(R.id.sign);
        final DrawerLayout drawerLayout=(DrawerLayout)findViewById(R.id.drawerLayout);
        drawerImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });
        gridView=(MyGridView)findViewById(R.id.gridView);
        mData=new ArrayList<>();
        adapter=new MyGridAdapter(mData, MainActivity.this);
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (isLongClickState == false) {
                    // 跳转到阅读界面
                } else {
                    if (mData.get(position).getIsCheck() == 1) {
                        mData.get(position).setIsCheck(0);
                    } else {
                        mData.get(position).setIsCheck(1);
                    }
                    adapter.notifyDataSetChanged();
                }
            }
        });

        gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                isLongClickState = true;
                for (Book book : mData) {
                    book.setIsShow(1);
                }
                mData.get(position).setIsCheck(1);
                adapter.notifyDataSetChanged();
                View v = LayoutInflater.from(MainActivity.this).inflate(R.layout.deletebook_popup, null, false);
                if (delBook == null) {
                    delBook = new PopupWindow(v, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                }
                delBook.setAnimationStyle(R.style.popup_anim);
                DisplayMetrics displayMetrics = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
                delBook.showAtLocation(view, Gravity.NO_GRAVITY, 0, displayMetrics.heightPixels - v.getMeasuredHeight());
                chooseAll = (Button) v.findViewById(R.id.chooseAll);
                chooseAll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (chooseAll.getText().equals("全选")) {
                            for (Book book : mData) {
                                book.setIsCheck(1);
                            }
                            chooseAll.setText("全不选");
                        } else {
                            for (Book book : mData) {
                                book.setIsCheck(0);
                            }
                            chooseAll.setText("全选");
                        }
                        adapter.notifyDataSetChanged();
                    }
                });
                Button finished = (Button) v.findViewById(R.id.finished);
                finished.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (Book book : mData) {
                            book.setIsCheck(0);
                            book.setIsShow(0);
                        }
                        chooseAll.setText("全选");
                        delBook.dismiss();
                        isLongClickState = false;
                        adapter.notifyDataSetChanged();
                    }
                });
                Button delete = (Button) v.findViewById(R.id.delete);
                delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
                        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.deletebook_dialog2_item, null);
                        alertDialog.setView(view);
                        final Dialog dialog = alertDialog.show();
                        Button yes = (Button) view.findViewById(R.id.yes);
                        final CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox);
                        yes.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (checkBox.isChecked()) {
                                    //删除手机的源文件

                                } else {
                                    ArrayList<Book> list = new ArrayList<Book>();
                                    for (Book book : mData) {
                                        if (book.getIsCheck() == 1) {
                                            list.add(book);
                                        }
                                    }
                                    dao.removeBooks(list);
                                    mData.removeAll(list);
                                    for (Book book : mData) {
                                        book.setIsCheck(0);
                                        book.setIsShow(0);
                                    }
                                    chooseAll.setText("全选");
                                    delBook.dismiss();
                                    isLongClickState = false;
                                    adapter.notifyDataSetChanged();
                                }
                                dialog.dismiss();
                            }
                        });
                        Button no = (Button) view.findViewById(R.id.no);
                        no.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });

                    }
                });
                return true;
            }
        });

        setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SettingActivity.class);
                startActivity(intent);
            }
        });

        about.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,AboutActivity.class);
                startActivity(intent);
            }
        });

        bookShop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到书城界面
            }
        });

        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到搜索书籍界面
            }
        });

        img1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.addbook_popup, null, false);
                if (addBook == null) {
                    addBook = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                }
                addBook.setFocusable(true);
                addBook.setOutsideTouchable(true);
                ColorDrawable colorDrawable = new ColorDrawable(0);
                addBook.setBackgroundDrawable(colorDrawable);
                addBook.setAnimationStyle(R.style.popup_anim);
                DisplayMetrics displayMetrics = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
                addBook.showAtLocation(v, Gravity.NO_GRAVITY, 0, displayMetrics.heightPixels - view.getMeasuredHeight());
                RelativeLayout relativeLayout1 = (RelativeLayout) view.findViewById(R.id.relative1);
                relativeLayout1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(MainActivity.this, LocalLeadToActivity.class);
                        addBook.dismiss();
                        startActivity(intent);
                    }
                });
                RelativeLayout relativeLayout2 = (RelativeLayout) view.findViewById(R.id.relative2);
                relativeLayout2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(MainActivity.this, YunBookActivity.class);
                        addBook.dismiss();
                        startActivity(intent);
                    }
                });
            }
        });

        centerHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sp=getSharedPreferences("SPIsLogin", Context.MODE_PRIVATE);
                if(sp.getInt("isLogin",0)==0){
                    View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.popup_window_login, null, false);
                    if (login == null) {
                        login = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    }
                    login.setFocusable(true);
                    login.setOutsideTouchable(true);
                    ColorDrawable colorDrawable = new ColorDrawable(0);
                    login.setBackgroundDrawable(colorDrawable);
                    login.setAnimationStyle(R.style.popup_anim);
                    DisplayMetrics displayMetrics = new DisplayMetrics();
                    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
                    login.showAtLocation(v, Gravity.NO_GRAVITY, 0, displayMetrics.heightPixels - view.getMeasuredHeight());
                    civ_login_qq=(CircleImageView)view.findViewById(R.id.civ_login_qq);
                    civ_login_qq.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            initQqLogin();
                            mTencent.login(MainActivity.this, SCOPE, loginListener);
                        }
                    });
                }else{
                    Toast.makeText(MainActivity.this,"你已登录，可在设置界面退出",Toast.LENGTH_SHORT).show();
                }
            }
        });

        sign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sp=getSharedPreferences("SPIsLogin",Context.MODE_PRIVATE);
                if(sp.getInt("isLogin",0)==0){
                    Toast.makeText(MainActivity.this,"请先登录",Toast.LENGTH_SHORT).show();
                }else{
                    Intent intent=new Intent(MainActivity.this,ConversionActivity.class);
                    startActivity(intent);
                }
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        mData.clear();
        mData.addAll(dao.findAllBook());
        adapter.notifyDataSetChanged();
        SharedPreferences sp=getSharedPreferences("SPIsLogin", Context.MODE_PRIVATE);
        if(sp.getInt("isLogin",0)==0){
            denglv.setText("点击登录");
            centerHead.setImageResource(R.mipmap.user_center_head_icon);
        }else{
            denglv.setText(sp.getString("userName",null));
            Glide.with(MainActivity.this).load(sp.getString("userImg",null)).into(centerHead);
        }
    }

    //初始化QQ登录分享的需要的资源
    private void initQqLogin(){
        mTencent =  Tencent.createInstance(APP_ID, this);
        //创建QQ登录回调接口
        loginListener = new IUiListener() {
            @Override
            public void onComplete(Object o) {
                //登录成功后回调该方法
                JSONObject jo = (JSONObject) o;
                //Log.e("COMPLETE:", jo.toString());
                String openID;
                try {
                    openID = jo.getString("openid");
                    QQId=openID;
                    String accessToken = jo.getString("access_token");
                    String expires = jo.getString("expires_in");
                    mTencent.setOpenId(openID);
                    mTencent.setAccessToken(accessToken, expires);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                login.dismiss();
            }

            @Override
            public void onError(UiError uiError) {
                //登录失败后回调该方法
                Toast.makeText(MainActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                login.dismiss();
                Log.e("LoginError:", uiError.toString());
            }

            @Override
            public void onCancel() {
                //取消登录后回调该方法
                Toast.makeText(MainActivity.this, "取消登录", Toast.LENGTH_SHORT).show();
            }
        };

        userInfoListener = new IUiListener() {
            @Override
            public void onComplete(Object o) {
                if(o == null){
                    return;
                }
                try {
                    JSONObject jo = (JSONObject) o;
                    //Log.e("JO:",jo.toString());
                    int ret = jo.getInt("ret");
                    String nickName = jo.getString("nickname");
                    String gender = jo.getString("gender");
                    figureurl_qq_1=jo.getString("figureurl_qq_1");
                    // Toast.makeText(MainActivity.this, "你好，" + nickName,Toast.LENGTH_LONG).show();
                    Glide.with(MainActivity.this).load(figureurl_qq_1).into(centerHead);
                    denglv.setText(nickName);
                    SharedPreferences sp=getSharedPreferences("SPIsLogin", Context.MODE_PRIVATE);
                    final SharedPreferences.Editor editor=sp.edit();
                    editor.putInt("isLogin", 1);
                    editor.putString("userName", nickName);
                    editor.putString("userImg",figureurl_qq_1);
                    editor.putString("QQId",QQId);
                    editor.commit();
                } catch (Exception e) {
                }
            }
            @Override
            public void onError(UiError uiError) {
            }
            @Override
            public void onCancel() {
            }
        };
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode,resultCode,data);
        if (requestCode == Constants.REQUEST_LOGIN) {
            if (resultCode == -1) {
                Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
                Tencent.handleResultData(data, loginListener);
                UserInfo info = new UserInfo(this, mTencent.getQQToken());
                info.getUserInfo(userInfoListener);
            }
        }
    }
}
